<?php
/**
 * Created by PhpStorm.
 * User: fuyu
 * Date: 2018/6/25
 * Time: 下午4:45
 */

namespace App\Http\Controllers;


use App\Logic\ExportFactory;
use Illuminate\Http\Request;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Spreadsheet;

class ExcelController extends Controller
{
    public function example()
    {
        $sheet = new Spreadsheet();
        $activeSheet = $sheet->getActiveSheet();
        $activeSheet->setCellValue('A1','Hello World!');

        $writer = new Xlsx($sheet);
        $writer->save(storage_path('exports/hell.xlsx'));
    }

    public function test()
    {
//        $sheet = new Spreadsheet();
//        $activeSheet = $sheet->getActiveSheet();
        $data = [
                    ['1111','222','333'],
                    ['1111','222','444'],
                    ['1111','333','444']
            ];
//        $activeSheet->fromArray($data);
//        $activeSheet->setCellValue('A1:C3',$data);
//        $writer = new Xlsx($sheet);
//        $writer->save(storage_path('exports/hello.xlsx'));
        $writer = new \XLSXWriter();
        $writer->writeSheet($data);
        $writer->writeToFile(storage_path('exports/hello.xlsx'));
    }

    public function load(Request $request)
    {
        set_time_limit(0);
        $type = $request->post('type');

        if (!in_array($type,ExportFactory::$ALL_EXPORT_TYPES)) {
            return jsonFail('非法的上传类型，请检查type字段');
        }
        if (!$request->hasFile('excel_file')) {
            return jsonFail('上传文件不能为空');
        }

        $file = $request->file('excel_file');
        $mimeType = $file->getMimeType();
        $availableMimes = [
            'application/vnd.ms-excel',
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        ];
        if (!in_array($mimeType,$availableMimes)) {
            return jsonFail('请上传正确的excel格式文件');
        }
        $fname = $file->getClientOriginalName();
        $folder = '/tmp/'.date('Y-m-d').'/';
        $file->move($folder,$fname);

        $filePath = $folder.$fname;
        $object = ExportFactory::create($type);
        $object->load($filePath);
        $cacheKey = $object->transform();
        if ($object->hasError()) {
            return jsonFail('源文件存在错误，请检查',['error'=>$object->getErrorData()]);
        } else {
            return jsonSuccess('数据预处理成功',['export_key'=>$cacheKey,'pre_export'=>$object->getTargetData()]);
        }
    }

    public function export(Request $request)
    {
        set_time_limit(0);
        $this->validate($request,[
            'type' => 'required',
            'export_key' => 'required'
        ]);
        $type = $request->get('type');
        $exportKey = $request->post('export_key');

        $object = ExportFactory::create($type);
        $filePath =  $object->writeToExcel($exportKey);
        return jsonSuccess('导出excel成功',['file_path'=>$filePath]);

    }

}